package command.receiver;

import java.io.BufferedWriter;
import java.io.IOException;
//import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import pojo.OnlineSocket;
import pojo.Protocol;
import util.ProtocolJSONConverter;
import command.BaseReceiver;

public class SendToGroupUsersReceiver extends BaseReceiver {

	public SendToGroupUsersReceiver(Map<String, OnlineSocket> connectedUsers,
			Protocol protocol) {
		super(connectedUsers, protocol);
	}

	@Override
	public Entry<Integer, List<Object>> action() throws IOException {
		
		Iterator<Map.Entry<String, OnlineSocket>> it = connectedUsers.entrySet().iterator();
		List<Object> offlineUsers = new ArrayList<>();

		while (it.hasNext()) {
			Map.Entry<String, OnlineSocket> entry = it.next();
			
			// Skip sender himself
			if (entry.getKey().equals(protocol.getFrom())) {
				continue;
			}

			OutputStream msgReceiverOut = entry.getValue().getOutputStream();

			try {
//				ObjectOutputStream objOut = new ObjectOutputStream(msgReceiverOut);
//				objOut.writeObject(protocol);
				
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(msgReceiverOut));
				writer.write(ProtocolJSONConverter.toJSON(protocol) + "\n");
				writer.flush();
			} catch (SocketException e) {
				String removedUser = entry.getKey();
				it.remove();
				offlineUsers.add(removedUser);
			}
		}
		
		if (offlineUsers.isEmpty()) {
			return null;
		}
		
		return new AbstractMap.SimpleEntry<Integer, List<Object>>(BaseReceiver.USER_OFFLINE, offlineUsers);
	}

}
